package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    //处理超时支付的订单
    @Scheduled(cron = "0 * * * * ?")
//    @Scheduled(cron = "1/5 * * * * ?")
    public void payOverTimeTask(){
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> list= orderMapper.selectByOrderTimeAndStatus(time, Orders.PENDING_PAYMENT);
        if(list!=null && list.size()>0){
            for (Orders orders : list) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("支付超时");
                orderMapper.update(orders);
            }
        }
    }

    //处理送达后未确认的订单
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void unconfirmedOrderTask(){
        LocalDateTime time = LocalDateTime.now().plusMinutes(-1);
        List<Orders> list = orderMapper.selectByOrderTimeAndStatus(time, Orders.DELIVERY_IN_PROGRESS);
        if(list!=null && list.size()>0){
            for (Orders orders : list) {
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }
}
